package com.example.administrator.xxnapp.friend;

import com.example.administrator.xxnapp.bean.UserBean;
import com.example.administrator.xxnapp.http.CustomStringCallback;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.List;

/**
 * Created by Administrator on 2018/5/13.
 */

public class FriendPresenter {
    private IViewFriend mIView;
    private IModelFriend mIModel;

    public FriendPresenter(IViewFriend mIView, IModelFriend mIModel) {
        this.mIView = mIView;
        this.mIModel = mIModel;
    }

    public void getFriends(int userId){
        mIModel.getFriends(userId)
                .execute(new CustomStringCallback() {
                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        mIView.getFriendsError(0,"请稍后重试");
                    }

                    @Override
                    public void onSuccessString(Gson gson, String responseBody) {
                        try {
                            JSONObject object = new JSONObject(responseBody);
                            if (object.getInt("result") == 200){
                                Type type = new TypeToken<List<UserBean>>() {
                                }.getType();
                                List<UserBean> userBeans = gson.fromJson(object.getJSONArray("data").toString(),type);
                                mIView.getFriendsSuccess(userBeans);
                            }else {
                                mIView.getFriendsError(object.getInt("result"),object.getString("message"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }
}
